package com.jcark.utilscode.ext

import android.text.Html
import android.text.Spanned
import android.text.TextUtils
import android.util.Patterns
import android.webkit.URLUtil
import android.widget.TextView
import com.blankj.utilcode.util.RegexUtils
import java.net.MalformedURLException
import java.net.URL
import java.util.Locale
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * 人民币符号 【¥】
 */
const val UNIT_RMB_1 = "¥"

/**
 *  人民币符号 【￥】
 */
const val UNIT_RMB_2 = "￥"

fun String.isEmail(): Boolean {
    val match = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"
    val pattern: Pattern = Pattern.compile(match)
    val matcher: Matcher = pattern.matcher(this)
    return matcher.matches()
}

/**
 * 是否为URL
 */
fun String.isURL(): Boolean {
    try {
        URL(this)
        return URLUtil.isValidUrl(this) && Patterns.WEB_URL.matcher(this).matches()
    } catch (e: MalformedURLException) {
    }
    return false
}

/**
 * 是否为指定文件类型，如【.pdf】
 */
fun String.isTypeFile(filetype: String): Boolean {
    return !TextUtils.isEmpty(this) && lowercase(Locale.getDefault()).endsWith(filetype)
}

fun String?.sub(textView: TextView, subLength: Int, suffix: String = "..."): String {
    var nameStr = this ?: ""
    if (!TextUtils.isEmpty(this)) {
        if (this!!.length > subLength) {
            nameStr = this.substring(0, subLength) + suffix
        }
        textView.visible()
        textView.text = nameStr
    } else {
        textView.gone()
    }
    return nameStr
}

fun String?.getPriceValue(): String {
    return if (TextUtils.isEmpty(this)) {
        ""
    } else {
        this!!.replace(UNIT_RMB_1, "")
            .replace(UNIT_RMB_2, "")
    }
}

/**
 * 获取匹配正则表达式的字符集合
 * @param regex 正则表达式
 * @param 起始索引的偏移量，应用在如【3.25年¥3.25日￥3.25分￥500，此时应带着符号匹配，否则无法定位，但匹配后又不想改变符号的样式时使用】
 */
fun String.getTextMatchIndexList(regex: String, offsetOfStart: Int = 0): List<TextMatchIndex> {
    val list = arrayListOf<TextMatchIndex>()
    val matcherList = RegexUtils.getMatches(regex, this)
    if (matcherList.isNotEmpty() && matcherList.size > 0) {
        var index = 0
        for (i in 0 until matcherList.size) {
            matcherList[i]?.let {
                val start = this.indexOf(it, index)
                if (start != -1) {
                    index = start + it.length
                    list.add(TextMatchIndex(it, if (index == 0) 0 + offsetOfStart else start + offsetOfStart, index))
                }
            }
        }
    }
    return list
}

fun String.toHtml(flag: Int = Html.FROM_HTML_MODE_LEGACY): Spanned {
    return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        Html.fromHtml(this, flag)
    } else {
        Html.fromHtml(this)
    }
}

data class TextMatchIndex(val text: String, val start: Int, val end: Int)
